<template>
  <div class="app-container">
    <div class="filter-container" style="margin-bottom:50px">
      <el-input v-model="listQuery.roleCode" placeholder="角色编号" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.roleName" placeholder="角色名称" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      
      <!-- <el-select v-model="listQuery.roleState" placeholder="角色状态" clearable style="width: 140px" class="filter-item">
        <el-option v-for="item in stateOptions" :key="item" :label="item" :value="item" />
      </el-select> -->
      <el-button class="filter-item" type="primary" icon="el-icon-search" style="margin-left:200px" @click="handleFilter()">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="fetchData()">
        重置
      </el-button>
    </div>


    <el-row :gutter="10" class="mb8" style="margin-bottom:20px">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd()"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          disabled
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          disabled
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          disabled
        >导出</el-button>
      </el-col>
    </el-row>

<!-- :data="list"  -->
<!-- :data="list.slice((currentPage-1)*pagesize,currentPage*pagesize)" -->
    <el-table 
        v-loading="listloading" 
        :data="list.slice((currentPage-1)*pagesize,currentPage*pagesize)" 
        element-loading-text="Loading"
        border
        highlight-current-row>

        <el-table-column align="center" label="序号">
          <template slot-scope="scope">
              {{ scope.row.roleId }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="角色编号">
          <template slot-scope="scope">
              {{ scope.row.roleCode }}
          </template>
        </el-table-column>
 
        <el-table-column align="center" label="角色名称">
          <template slot-scope="scope">
              {{ scope.row.roleName }}
            </template>
        </el-table-column>
 

        <!-- <el-table-column align="center" label="角色状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.roleState | stateFilter">
              {{ scope.row.roleState }}
            </el-tag>
          </template>
        </el-table-column> -->

        <el-table-column label="Actions" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleEdit(row)" plain>
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)" plain>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5,10,15,20,25.30]"
        :page-size="pagesize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total">
    </el-pagination>

    <!-- //对话框   -->
    <el-dialog :title="formTitle[dialogState]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="角色编号" prop="roleCode" label-width="80px">
          <el-input v-model="temp.roleCode" placeholder="请填写用户编号" />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName" label-width="80px">
          <el-input v-model="temp.roleName" placeholder="请填写用户名称" />
        </el-form-item>

        <!-- <el-form-item label="状态" prop="roleState" label-width="80px">
          <el-select v-model="temp.roleState" class="filter-item" placeholder="请选择用户状态" >
            <el-option v-for="item in stateOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogState==='add'?AddData():editData()">
          确认
        </el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { editRoleInfo, getList } from '@/api/userRole'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { addRoleInfo } from '@/api/userRole'
import { findRoleInfo,deleteRoleInfo } from '@/api/userRole'
// import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  components: { Pagination },
  //过滤器
  filters:{
    stateFilter(state){
      const stateMap = {
        启用:'success',
        禁用:'danger'
      }
      return stateMap[state]
    }
  },
  data() {
    return {
      list:[],  //list:null
      total:0,
      listloading: true,
      dialogFormVisible: false,
      //查找
      listQuery:{
        roleCode:undefined,
        roleName:undefined
      },
      //表格
      temp:{
        roleId:undefined,
        roleCode:'',
        roleName:''
      },
      // 校验规则
      rules:{
        //验证角色编号——只能数字+英文,不能包含特殊字符
        roleCode: [{ required: true, message: '用户编号不能为空', trigger: 'blur' },
          {pattern:/^[a-zA-Z0-9]+$/,message: '不能包含特殊字符', trigger: ['blur','change']},
          {min:2, max:6 ,message:'角色编号不少于2位不长于6位',trigger:['blur','change']}],
        roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' },
          {min:2, max:10 ,message:'角色名称不少于2位不长于10位',trigger:['blur','change']}]
      },
      //数据分页
      currentPage:  1,    //初始页
      pagesize: 5,      //每页的数据
      arr:[],    //你的数据
      stateOptions: ['启用', '禁用'],      //用户状态选择
      roles:['管理员','普通用户'],       //角色
      formTitle:{       //弹窗标题
        add:'新增角色信息',
        edit:'修改角色信息'
      },
      dialogState:''    //弹窗标题 
    }
  },
  created() {
    this.fetchData()
    console.log("currentPage",this.currentPage)
    console.log("pagesize",this.pagesize)
  },
  methods: {
    //查找函数
    handleFilter() {
      console.log('我被点击了!')
      this.listloading = true
      findRoleInfo(this.listQuery).then(response =>{
        this.list = response.data.items
        this.total = response.data.total
        //消息提示
        this.$notify({
          title: 'Success',
          message: '查找成功',
          type: 'success',
          duration: 2000
        })
        console.log(this.list)
        this.listloading = false
      })
    },
    //每页显示几条
    handleSizeChange(val){
      this.pagesize = val;  //获取pagesize里的每页显示几条数据，赋给自定义的PageNUm
      console.log("当前页面显示xxx条",val);
      this.currentPage = 1;
    },
    //分页函数
    handleCurrentChange(val){
      this.currentPage = val;  
      console.log("当前页面显示xxx页",val)
    },  
    fetchData(){
        this.listloading = true
        getList().then(response =>{
            this.list = response.data.items
            this.total = response.data.total
            console.log(this.list)
            this.listloading = false
        })
    },
    //每次点击添加按钮重置表单
    resetTemp(){
      this.temp = {
        roleId:undefined,
        roleCode:'',
        roleName:''
      }
    },
    //添加按钮触发事件 Add按钮绑定函数
    handleAdd(){
      this.resetTemp()
      this.dialogState = 'add'
      this.dialogFormVisible = true
      this.$nextTick(()=>{
        //重置表单校验
        this.$refs['dataForm'].clearValidate()
      })
      console.log("新增按钮被点击了！")
    },
    //新增用户信息表单确定按钮
    AddData(){
      console.log("表单中的数据:",this.temp)
      this.$refs['dataForm'].validate((valid)=>{
        if(valid){
          addRoleInfo(this.temp).then(()=>{
            // this.list.unshift(this.temp)
            this.dialogFormVisible = false
            //消息提示
            this.$notify({
              title: 'Success',
              message: '添加成功！',
              type: 'success',
              duration: 2000
            })
            this.fetchData()
          })
        }
      })
    },
    //编辑操作
    handleEdit(row){
      this.temp = Object.assign({}, row) // copy obj
      this.dialogState = 'edit'
      this.dialogFormVisible = true
      console.log("编辑按钮被点击了")
      this.$nextTick(() => {
        //重置表单校验
        this.$refs['dataForm'].clearValidate()
      })
    },
    //编辑信息
    editData(){
      this.$refs['dataForm'].validate((valid)=>{
        if(valid){
          const tempData = Object.assign({}, this.temp)
          editRoleInfo(tempData).then(()=>{
            //findIndex()寻找下标，满足返回位置，反之-1
            // const index = this.list.findIndex(v => v.id === this.temp.id)
            //splice从index位置，替换1个，用this.temp的内容
            // this.list.splice(index, 1, this.temp)
            this.fetchData()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '修改成功！',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    //删除操作
    handleDelete(row,index){
      this.temp = Object.assign({}, row) // copy obj
      // this.dialogFormVisible = true
      //vue2直接用$confirm
      this.$confirm('是否删除该条信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //删除
          // this.list.splice(index, 1);
          deleteRoleInfo(this.temp.roleId).then(res=>{
            this.$message({
              type: 'success',
              message: res.message
            });
            this.fetchData()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      console.log("删除按钮被点击了")
    }
  }
}
</script>
